package com.jy.bo.common.conf.interceptor;

/**
 * @author binary
 * 2019-04-30
 */

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * RestTemplate http请求日志拦截器
 */
@Component
public class HttpLogRequestInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HttpLogRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        logger.info("===========================【request begin】================================================\n"
                        + "【URI】         : {}\n"
                        + "【Method】      : {}\n"
                        + "【Header】      : {}\n"
                        + "【Request body】: {}\n"
                        + "==========================【request end】================================================"
                , request.getURI(), request.getMethod(), JSON.toJSONString(request.getHeaders()), new String(body, StandardCharsets.UTF_8));
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            line = bufferedReader.readLine();
        }
        logger.info("============================【response begin】==========================================\n"
                        + "【Status code】  : {}\n"
                        + "【Status text】  : {}\n"
                        + "【Headers】      : {}\n"
                        + "【Response body】: {}\n"
                        + "=======================【response end】================================================="
                , response.getStatusCode(), response.getStatusText(), response.getHeaders(), inputStringBuilder.toString());
    }
}
